<template>
  <view class="ai-tabs-navItem">
    <view class="ai-tabs-navLink" :class="{active}" type="button" role="tab" :aria-selected="active" @click="onclick">
      <text :class="textClassName">{{label}}</text>
    </view>
    <view class="ai-tabs-navPointer" :style="pointerStyles"></view>
  </view>
</template>

<script>
  export default {
    name: "ai-tab-item",
    emits: ["click"],
    props: {
      label: String,
      active: {
        type: Boolean,
        default: false
      },
      value: String,
      tabIndex: Number,
    },
    data() {
      return {
        textWidth: 0
      };
    },
    computed: {
      textClassName: {
        get: function() {
          let tabIdx = this.tabIndex
          return `tabs-item-${tabIdx}-text`
        }
      },
      pointerStyles: {
        get: function() {
          if (!this.active) {
            return "width:0"
          }
          const pointerWidth = Math.max(this.textWidth - 16, 26)
          return `left:50%;transform:translateX(-50%);width:${pointerWidth}px`
        }
      }
    },
    methods: {
      onclick() {
        let tabIdx = this.tabIndex
        const selectTabTextClass = `.tabs-item-${tabIdx}-text`
        const query = uni.createSelectorQuery().in(this)
        query.select(selectTabTextClass).boundingClientRect(data => {
          // console.log(JSON.stringify(data))
          this.textWidth = data.width
        }).exec()
        
        this.$emit("click", {value: this.value, tabIndex: this.tabIndex})
      }
    }
  }
</script>

<style lang="scss">
  @import "@/styles/_var.scss";
  

  .ai-tabs-navItem {
    position: relative;
    display: inline-block;
    flex: 1;
    text-align: center;
  }

  .ai-tabs-navLink {
    padding: $tabs-nav-link-padding;
    border: $tabs-nav-link-border;
    border-radius: $tabs-nav-link-border-radius;
    background: $tabs-nav-link-bg;
    color: $tabs-nav-link-color;
    font-size: $tabs-nav-link-font-size;
    transition: $tabs-nav-link-transition;
    line-height: 1.6;

    &:focus:not(:focus-visible) {
      outline: 0;
    }

    &:hover {
      cursor: pointer;
      color: $tabs-nav-link-hover-color;
    }

    &.active {
      position: relative;
      z-index: 1;
      color: $tabs-nav-link-active-color;
      font-weight: bold;
    }
  }
  
  .ai-tabs-navPointer {
    position: absolute;
    left: 0;
    bottom: 0;
    height: $tabs-nav-pointer-height;
    background: $tabs-nav-pointer-bg;
    border-radius: $tabs-nav-pointer-border-radius;
    transition: $tabs-nav-pointer-transition;
  }
</style>